<template>
  <q-card class="my-card">
    <q-card-section class="bg-primary text-white">
      <div v-if="!inEdit">
        <div class="text-h6">{{prefix.name}}</div>
        <div class="text-subtitle2">{{prefix.description}}</div>
      </div>

      <q-form v-else ref="prefixForm">
        <q-input
            outlined
            dense
            color="grey-3"
            v-model="prefix.name"
            label="前缀名称"
            lazy-rules
            :rules="[ (val: String) => val && val.length > 0 && val.length < 10 || '名称在10个字符以内的']"
            :autofocus="true"
        />

        <q-input
            outlined
            dense
            color="grey-3"
            v-model="prefix.description"
            label="前缀说明"
            lazy-rules
            :rules="[ (val: String) => val && val.length > 0 && val.length < 10 || '说明在10个字符以内']"
        />
      </q-form>

    </q-card-section>

    <q-separator />

    <q-card-actions align="right">
      <q-btn dense outline :label="editBtnLabel" color="primary" size="md" @click="editPrefix(item.id)"/>
      <q-btn v-if="!inEdit" dense outline label="删除" color="red-4" size="md" @click="remove(item.id)"/>
      <q-btn v-if="inEdit" dense outline label="删除" color="red-4" size="md"
             :disabled="editModeDeleteBtnDisable"
             @click="cleanUnSavedPrefix" />
    </q-card-actions>
  </q-card>
</template>

<script lang="ts">
import {computed, defineComponent, PropType, ref} from "vue";
import {QBtn, QCard, QCardActions, QCardSection, QForm, QInput, QSeparator, QToggle} from "quasar";
import {Prefix} from "../../../types/prefix";
import {usePrefix} from "../../../hooks/usePrefix";
import md5Hex from "md5-hex";
import {showError, showSuccess} from "../../../utils/notify";

export default defineComponent({
  name: "PrefixItem",
  components: {
    QBtn,
    QSeparator,
    QCard,
    QCardSection,
    QCardActions,
    QForm,
    QInput,
    QToggle,
  },
  props: {
    item: {
      type: Object as PropType<Prefix>,
      required: true
    }
  },
  setup(props, context) {

    const prefix = ref<Prefix>(props.item)

    const prefixHash = md5Hex(JSON.stringify(prefix.value))

    const prefixForm = ref(null)

    const {add, edit, remove, cleanUnSavedPrefix} = usePrefix()

    const inEdit = ref(prefix.value.id === -1)

    const editBtnLabel = computed(() => {
      return inEdit.value ? '保存' : '编辑'
    })

    // 编辑状态下，删除按钮是否可用。当前缀的 ID 是 -1 时可用，即新增前缀时
    const editModeDeleteBtnDisable = computed(() => {
      return prefix.value.id !== -1
    })

    function editPrefix(prefixId: number) {
      if (!inEdit.value) { // 非编辑模式，切换模式
        inEdit.value = true
        return
      }
      // @ts-ignore
      prefixForm.value.validate().then(success => {
        if (success) {
          // 新增标签
          if (!editModeDeleteBtnDisable.value) {
            add(prefix.value).then(res => {
              showSuccess('新增前缀成功')
              inEdit.value = false
            }).catch(err => {
              showError('新增前缀失败')
              inEdit.value = false
            })
          } else {
            const currentPrefixHash = md5Hex(JSON.stringify(prefix.value))
            if (currentPrefixHash === prefixHash) {
              showSuccess('前缀编辑成功')
              inEdit.value = false
              return
            }
            edit(prefix.value).then(res => {
              showSuccess('前缀编辑成功')
              inEdit.value = false
            }).catch(err => {
              showError('前缀编辑失败')
              inEdit.value = false
            })
          }
        }
      })
    }

    return {
      prefixForm,
      prefix,
      inEdit,
      editBtnLabel,
      editModeDeleteBtnDisable,
      editPrefix,
      remove,
      cleanUnSavedPrefix
    }
  }
})
</script>

<style scoped>
  .my-card {
    width: 100%;
    max-width: 200px;
  }
  .env-switch {
    position: absolute;
    right: 0;
    top: 0;
  }
</style>